package com.igeek.config.ch01;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;


@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ICount){
            ICount proxy = (ICount) Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            String methodName = method.getName();
                            System.out.println("日志追踪 The method "+methodName+" begin with "+ Arrays.toString(args));
                            Object result =null;
                            try {
                                result=method.invoke(bean,args);
                                System.out.println("日志追踪 The method "+methodName+" end with "+result);
                            }catch (Exception e){
                                System.out.println("日志追踪 The method "+methodName+" 发生异常 "+e.getMessage());
                                e.printStackTrace();
                            }
                            System.out.println("日志追踪 The method "+methodName+" end with ");

                            return result;
                        }
                    }
            );
            return proxy;
        }
        return bean;
    }
}
